package com.edais.actions;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.edais.domain.ErrorMessageSetting;
import com.edais.domain.User;
import com.edais.service.CenterService;
import com.edais.service.JkxyService;
import com.edais.service.PointService;
import com.edais.service.SMSService;
import com.edais.service.ShopBuyService;
import com.edais.service.ShopVouchersService;
import com.edais.service.SystemIdWorkerService;
import com.edais.service.UserService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.MD5;
import com.edais.util.Message;
import com.edais.util.StrUtil;
import com.edais.util.StringUtil;

@Controller
@RequestMapping("/shopbuy")

public class ShopBuyAction implements Serializable {
	
	private static final long serialVersionUID = 1L;

	private static final Log logger = LogFactory.getLog(ShopBuyAction.class);

	@Autowired
	private UserService userService;
	
	@Autowired
	private CenterService centerService;

	@Autowired
	private ShopBuyService shopBuyService;

	@Autowired
	private JkxyService jkxyService;
	
	@Autowired
	private SystemIdWorkerService systemIdWorkerService;
	
	@Autowired
	private ShopVouchersService shopVouchersService;
	
	@Autowired
	private PointService pointService;
	@Autowired
	private SMSService sMSService;

	/**
	 * @Description:
	 * @param @param request
	 * @param @param response
	 * @param @throws Exception
	 * @return void
	 * @throws
	 * @author chenshufeng
	 * @date 2016-8-11
	 */
	@RequestMapping(value = "/buy")
	public void buy(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.info("javaservice>>ShopBuyAction>>buy start");
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);// 解密请求参数
		String userId = paramsMap.get("userId");// 用户id
		String passwordCash = paramsMap.get("passwordCash");// 用户密码
		String lcOrderId = paramsMap.get("lcOrderId");// 理财ID
		String financeType = paramsMap.get("financeType");// 理财类型
		String goodsName = paramsMap.get("goodsName");// 商品名称
		String buyQuantity = paramsMap.get("buyQuantity");// 购买数量
		String investAmount = paramsMap.get("investAmount");// 投资金额
		String amount = paramsMap.get("amount");// 投资总额
		String term = paramsMap.get("term");// 期数
		String annualRate = paramsMap.get("annualRate");// 利率
		String expectAmount = paramsMap.get("expectAmount");// 预期收益
		String buyMedia = paramsMap.get("buyMedia");// 购买媒介
		String agreementNo = paramsMap.get("agreementNo");
		String assetNo = paramsMap.get("assetNo");
		try {
			Map<String, String> pageMode = new HashMap<String, String>();
			pageMode.put("userId", userId);
			pageMode.put("passwordCash", passwordCash);
			pageMode.put("lcOrderId", lcOrderId);
			pageMode.put("financeType", financeType);
			pageMode.put("investAmount", investAmount);
			pageMode.put("buyQuantity", buyQuantity);
			pageMode.put("term", term);
			pageMode.put("annualRate", annualRate);
			pageMode.put("expectAmount", expectAmount);
			pageMode.put("buyMedia", buyMedia);
			pageMode.put("amount", amount);
			pageMode.put("agreementNo", agreementNo);
			pageMode.put("assetNo", assetNo);
			try {
				String agreementautoid=systemIdWorkerService.getCurrentNo();
				logger.info("商城购买 :agreementautoid="+agreementautoid);
				pageMode.put("agreementAutoid", agreementautoid);//协议编号
			} catch (Exception e1) {
				logger.error("商城购买加入自动生成的协议编号发生异常:"+e1);
				e1.printStackTrace();
				pageMode.put("agreementAutoid", "");//
			}
			buyCheck(pageMode);//检查数据

			// 生成理财主逻辑=============================

			Map<String, Object> retMap = new HashMap<String, Object>();
			retMap = shopBuyService.createOrderFinance(pageMode);
			logger.info("商城购买返回结果：" + retMap.toString());

			if (!Consts.SUCCESS_CODE.equals(retMap.get("rescode"))) {
				String result = CommonUtil.setResultStringCn(retMap,
						retMap.get("rescode").toString(), "", retMap.get("resmsg").toString());
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			//送一元购券
			String mobile = String.valueOf(userService.getUserMobile(userId).get("mobile"));// 通过用户ID查询使用手机号
			try {
				logger.info("用户"+userId+"商城购买元赠送电商一元购券");
				Map<String,Object> addParam = new HashMap<String, Object>();
				addParam.put("userId", userId);
				addParam.put("mobile", mobile);
				addParam.put("voucherId",1);
				addParam.put("source","2");//兑换券来源 1：K码激活赠送 2：发现购物赠送 3：新增定期赠送 4：活动赠送 5：积分兑换 0：其他
				Map<String, String> addResult = shopVouchersService.addShopVouchers(addParam);
				if(!Consts.SUCCESS_CODE.equals(addResult.get("rescode"))){
					logger.info("用户"+userId+"商城购买理财，赠送电商一元购券失败！");
				}
			} catch (Exception e) {
				logger.error("用户"+userId+"商城购买理财，赠送电商一元购券失败！",e);
			}
			//定期购买成功，赠送积分
			try {
				Map<String,Object> paraMap=new HashMap<String,Object>();
				String orderId=retMap.get("orderId")==null?"":(String)retMap.get("orderId");
				paraMap.put("userId", userId);
				paraMap.put("mobile", mobile);
				paraMap.put("orderId", orderId);
				paraMap.put("dingQiAmount", amount);
				paraMap.put("dingQiPeriods", term); //期数
				paraMap.put("dingQiRemanDays", term); //天数
				pointService.shopPoint(paraMap);
			} catch (Exception e) {
				logger.error("用户商城购买"+mobile+"，赠送积分发生异常：",e);
			}
			// 发送短信=============================
//			sMSService.getSMS(userId + "", "sms02001", investAmount,
//					(String) retMap.get("cpType"));
			//推送购买微信/短信接口
			shopBuyService.sendMeidaAndSMS(userId, "108",(String) retMap.get("cpType"),goodsName,amount,buyQuantity);
			//发送个推消息----add by gongyanlan
			String smsNo="sms02001";//投资,config_sms表中参数,
			String cpType=(String) retMap.get("cpType");
			String[] smsParams={amount,cpType,""};
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("userId", userId);
			map.put("mobile", mobile);
			map.put("title", "投资通知");//标题
			map.put("messageDetailTypeNew", "4");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
			map.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
			map.put("smsParams", smsParams);//消息模板里需要替换的变量
			map.put("smsNo", smsNo);
			sMSService.sendGetuiMSG(map);
			// 生成定期借款协议=============================
//			try {
//				Map<String, String> paraMap = new HashMap<String, String>();
//				paraMap.put("orderId", retMap.get("orderId") == null ? ""
//						: (String) retMap.get("orderId"));
//				jkxyService.setJkxyForK("loanAgreement", paraMap);
//			} catch (Exception e) {
//				logger.error("商城购买借款协议失败异常" + e);
//			}
			try {
				Map<String,String> paraMap=new HashMap<String,String>();
				paraMap.put("orderId", retMap.get("orderId")==null?"":(String)retMap.get("orderId"));
				jkxyService.setJkxy("loanAgreement",paraMap);
			} catch (Exception e) {
				logger.info("商城购买借款协议失败异常"+e.getCause());
				e.printStackTrace();
			}
			//ouyy定期购买成功，生成借款协议成功，将文件名更新到order表中
			try {
				Map<String,String> paraMap=new HashMap<String,String>();
				String orderId=retMap.get("orderId")==null?"":(String)retMap.get("orderId");
				paraMap.put("userId", userId);
				paraMap.put("orderId", orderId);
				paraMap.put("agreementFilename", StrUtil.fileNameMD5(orderId));
				centerService.updateOrderFilename(paraMap);
			} catch (Exception e) {
				// TODO: handle exception
				logger.info("更新协议文件名到order表中发生异常"+e);
				e.printStackTrace();
			}

			// 处理返回结果=============================
//			UserInfo userInfo = userService.getUserInfo(userId);
//			retMap.put("mobile", userInfo.getPhone_no());//手机
//			retMap.put("realName", userInfo.getReal_name());//真实姓名
			String result = CommonUtil.setResultStringCn(retMap,
					Consts.SUCCESS_CODE, "", "");
			
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.error("商城购买 异常:" + e);
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, "", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}
	
	
	/**
	 * 获取商品图片详情
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/goodsDetailImg")
	public void goodsDetailImg(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);// 解密请求参数
		Map<String, Object> resMap = new HashMap<String, Object>();
		String goodsId = paramsMap.get("goodsId");// goodsId
		try {
			if (StringUtil.isEmpty(goodsId)) {
				logger.info("获取商品图片详情：goodId为空");
				String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
						Consts.CHECK_CODE, "", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				// 处理返回结果
				CommonUtil.responseJson(result, response);
				return;
			}
			
			Map<String, Object> parmeterMap = new HashMap<String, Object>();
			parmeterMap.put("goodsId", goodsId);
			
			resMap = shopBuyService.goodsDetailImg(parmeterMap);
			
			String picDetailLink = (String)resMap.get("picDetailLink");
			resMap.put("picDetailLink", picDetailLink);
			String result = CommonUtil.setResultStringCn(resMap,
					Consts.SUCCESS_CODE, "", "");
			
			CommonUtil.responseJson(result, response);

		} catch (Exception e) {
			logger.error("获取商品图片详情:" + e);
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
					Consts.ERROR_CODE, "", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
	}

	private Map<String, String> buyCheck(Map<String, String> paramsMap)
			throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();
		
		String userId = paramsMap.get("userId");// 用户id
		String passwordCash = paramsMap.get("passwordCash");// 交易密码
		String amount = paramsMap.get("amount");// 总额
		
		// 用户是否登陆
		if (StringUtils.isBlank(userId)) {
			logger.info("商城购买：用户id为空");
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("resmsg",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);	
			return resMap;
		}
		//实名认证
		User user = userService.getUserDetail(userId);//获取用户是否实名认证,对于实名认证用户取得身份证号和姓名
		if (!"1".equals(user.getIs_create_acct()) || !"Y".equals(user.getIdcard_validate())) {
			logger.info("商城购买：用户没有经过实名认证");
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("resmsg", "请先实名认证！");
			return resMap;
		}
		
		// 获取该用户的余额
		Map<String, Object> pageMode = new HashMap<String, Object>();
		pageMode.put("userId", userId);
		String acctBalanceStr = "0.00";// 余额
		Map balanceMap = centerService.getCusBalance(pageMode);
		if (balanceMap != null && "00000".equals(balanceMap.get("rescode"))) {
			acctBalanceStr = balanceMap.get("ACCTBALANCE") + "";
		} else {
			logger.info("商城购买：" + balanceMap.get("resmsg"));
			resMap.put("rescode", Consts.ERROR_CODE);
			resMap.put("resmsg", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}

		// 余额检查
		if ("0.00".equals(acctBalanceStr) || StringUtils.isBlank(acctBalanceStr)) {
			logger.info("商城购买：余额不足。余额为:" + String.valueOf(acctBalanceStr));
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("resmsg", Message.CnDescriptionExpression.BALANCE_IS_INCORRECT);
			return resMap;
		}

		BigDecimal acctBalanceBD = new BigDecimal(acctBalanceStr);// 余额

		// 余额-投资金额 < 0
		if (acctBalanceBD.compareTo(new BigDecimal(amount)) < 0) {
			logger.info("商城购买：余额不足。余额差:" + acctBalanceBD.subtract(new BigDecimal(amount)));
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("resmsg", Message.CnDescriptionExpression.BALANCE_IS_INCORRECT);
			return resMap;
		}
		// 交易密码验证
		if (StringUtils.isBlank(passwordCash)) {
			logger.info("商城购买：交易密码为空!");
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("resmsg", "您的密码不正确，请重新输入！");
			return resMap;
		}
		String passwordMd5 = MD5.md5(passwordCash);
		if (!passwordMd5.equals(user.getPassword_cash())) {
			logger.info("商城购买：交易密码错误，请重新输入！");
			resMap.put("rescode", Consts.CHECK_CODE);
			resMap.put("resmsg", "您的密码不正确，请重新输入！");
			return resMap;
		}
		//购买的商品是否存在
//		GoodsInfo goodsInfo = goodsService.selectGoodsInfo(categoryId);
//		if(null == goodsInfo){
//			logger.info("商城购买：该商品不存在！");
//			resMap.put("rescode", Consts.CHECK_CODE);
//			resMap.put("resmsg", Message.CnDescriptionExpression.BUSINESSE_ERROR);
//			return resMap;
//		}
//		// 商品库存是否足够
//		BigDecimal remainQuantity = goodsInfo.getRemainQuantity();
//		if(remainQuantity.compareTo(new BigDecimal(buyQuantity)) == -1){
//			logger.info("商城购买：该商品库存不足！");
//			resMap.put("rescode", Consts.CHECK_CODE);
//			resMap.put("resmsg", "对不起，您购买的商品已售完！");
//			return resMap;
//		}
//		//预期收益是否正确
//		BigDecimal expectAmount = null;
//		FinanceInfo financeInfo = goodsService.selectFinanceInfo(lcOrderId);//获取理财信息
//		if(null != financeInfo){
//			BigDecimal perServingAmount = financeInfo.getPerServingAmount();
//			BigDecimal rate = financeInfo.getAnnualRate();
//			//计算预期收益
//			BigDecimal day = new BigDecimal(365);
//			expectAmount = perServingAmount.multiply(rate).multiply(new BigDecimal(financeInfo.getTerm())).divide(day, 2);
//		}else{
//			logger.info("商城购买：未获取到对应的理财信息！");
//			resMap.put("rescode", Consts.CHECK_CODE);
//			resMap.put("resmsg", Message.CnDescriptionExpression.BUSINESSE_ERROR);
//			return resMap;
//		}
//		if(expectAmount.compareTo(new BigDecimal(expectIncomeAmount)) != 0){
//			logger.info("商城购买：预期收益不正确！");
//			resMap.put("rescode", Consts.CHECK_CODE);
//			resMap.put("resmsg", Message.CnDescriptionExpression.BUSINESSE_ERROR);
//			return resMap;
//		}
		return null;
	}
	
	/**
	 * @Description: 获取错误信息
	 * @param @param errorMap
	 * @param @return
	 * @return String
	 * @throws
	 * @author chenshufeng
	 * @date 2016-8-11
	 */
	private String getErrorMsg(Map<String, Object> errorMap) {
		ErrorMessageSetting emsEntity = (ErrorMessageSetting) errorMap
				.get("errorMessage");
		String emsStr = "";
		if (null != emsEntity) {
			emsStr = emsEntity.getMessage_content();
		}
		return emsStr;
	}
}
